//
//  SYS_MessageHomeVC.m
//  System_App
//
//  Created by czy001 on 2017/12/1.
//  Copyright © 2017年 czy001. All rights reserved.
//

#import "SYS_MessageHomeVC.h"
#import "SYS_MessageHomeCell.h"
#import "EaseConversationListViewController.h"

@interface SYS_MessageHomeVC ()

@property (nonatomic, strong) EaseConversationListViewController *contactListVC;

@property (nonatomic, strong) SYS_DisplayWithBlankView *alertView;

@end

@implementation SYS_MessageHomeVC

- (id)init
{
    self=[super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getChatMessage:) name:@"MESSAGEDATA" object:nil];
    }
    return self;
}

- (void)getChatMessage:(NSNotification *)not
{
    _messageArr=not.object;
    if (_messageArr.count>0) {
        _alertView.hidden=YES;
    }
    [self loadTableView];
}

- (void)loadTableView
{
    NSArray *array=[[NSUserDefaults standardUserDefaults] objectForKey:@"TOPMessage"];
    _topArr=[NSMutableArray arrayWithArray:array];
    
    _dataArr=[NSMutableArray arrayWithArray:_messageArr];
    for (int i=0; i<[_topArr count]; i++) {
        NSString *messageId=[_topArr objectAtIndex:i];
        for (int j=0; j<[_dataArr count]; j++) {
            id<IConversationModel> model = [self.dataArr objectAtIndex:j];
            if ([model.conversation.conversationId isEqualToString:messageId]) {
                [_dataArr removeObject:model];
                [_dataArr insertObject:model atIndex:i];
                break;
            }
        }
    }
    [_mainTableView reloadData];
    if (_dataArr.count == 0) {
        _alertView.hidden=NO;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor=RGBACOLOR(242, 242, 242, 1);
    
    [self viewDisplay];
    //    返回按钮
    [self.navigationItem setHidesBackButton:YES];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"SYS_Public_back" highImage:nil title:nil target:self action:@selector(backToPrevious)];

}

- (void)viewDisplay
{
    _operation=[[DSDataBaseOperation alloc] init];
    
    //    [_contactListVC tableViewDidTriggerHeaderRefresh];
    
    _mainTableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT-45-NavBarHeight-TabBarHeight) style:UITableViewStylePlain];
    _mainTableView.delegate=self;
    _mainTableView.dataSource=self;
    //    _mainTableView.separatorStyle=uitableviewsele
    [_mainTableView registerNib:[UINib nibWithNibName:@"SYS_MessageHomeCell" bundle:nil] forCellReuseIdentifier:@"SYS_MessageHomeCell"];
    _mainTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_mainTableView];
    
    _alertView=[[SYS_DisplayWithBlankView alloc] initWithFrame:CGRectMake(0, 0, 150, 150)];
    _alertView.photo.image=[UIImage imageNamed:@"zanwuxiaoxi"];
    _alertView.title.text=@"您还没有消息~";
    _alertView.center=CGPointMake(_mainTableView.center.x, 140);
    _alertView.hidden=YES;
    [self.view addSubview:_alertView];
}

- (void)backToPrevious
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    //  section头背景
//    UIView *bjView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 20)];
//    bjView.backgroundColor=RGBACOLOR(242, 242, 242, 1);
//
//    return bjView;
//
//}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [EaseConversationCell cellIdentifierWithModel:nil];
    EaseConversationCell *cell = (EaseConversationCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[EaseConversationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    if ([self.dataArr count] <= indexPath.row) {
        return cell;
    }
    
    id<IConversationModel> model = [self.dataArr objectAtIndex:indexPath.row];
    cell.model = model;
    if ([_topArr containsObject:model.conversation.conversationId]) {
        cell.contentView.backgroundColor=RGBACOLOR(250, 250, 250, 1);
    }
    
    if (model.conversation.type == EMConversationTypeChat) {
        //  比较当前消息是否是最新的，如果是插入数据
        if ([_operation compareMessageFromTime:model.conversation.latestMessage]) {
            [_operation insertUserInfo:model.conversation.latestMessage];
        }
        // 获取用户信息
        DGHUserInfo *info=[_operation searchUserInfoWithHXName:model.conversation.conversationId];
        //        NSLog(@"---%@---%@",info.headpic,model.conversation.conversationId);
        if (info.headpic.length>0 || info.username.length>0) {
            cell.titleLabel.text=info.username;
            
            NSString *defaultImage=@"";
            if ([model.conversation.latestMessage.from hasPrefix:@"sto"]) {
                defaultImage=@"message_store_default";
            }
            else
            {
                defaultImage=@"message_own_default";
            }
            [cell.avatarView.imageView sd_setImageWithURL:[NSURL URLWithString:info.headpic] placeholderImage:[UIImage imageNamed:defaultImage]];
        }
        else
        {
            NSDictionary *ext=model.conversation.latestMessage.ext;
            NSDictionary *senderInfo=[SYS_HelpModel dictionaryWithJsonString:ext[@"data"]];
            if ([ext[@"fromType"] hasPrefix:@"own"]) {
                [cell.avatarView.imageView sd_setImageWithURL:[NSURL URLWithString:JSON(senderInfo[@"photo"])] placeholderImage:[UIImage imageNamed:@"message_store_default"]];
                cell.titleLabel.text=JSON(senderInfo[@"nickName"]);
                if ([JSON(senderInfo[@"nickName"]) length]>0 || [JSON(senderInfo[@"photo"]) length]>0) {
                    EMMessage *mes=[[EMMessage alloc] initWithConversationID:nil from:ext[@"fromType"] to:ext[@"fromType"] body:nil ext:@{@"name":JSON(senderInfo[@"nickName"]),@"image":JSON(senderInfo[@"photo"])}];
                    [_operation insertUserInfo:mes];
                }
            }
            else if ([ext[@"fromType"] hasPrefix:@"sto"]) {
                [cell.avatarView.imageView sd_setImageWithURL:[NSURL URLWithString:JSON(senderInfo[@"photo"])] placeholderImage:[UIImage imageNamed:@"message_own_default"]];
                cell.titleLabel.text=JSON(senderInfo[@"nickName"]);
                if ([JSON(senderInfo[@"nickName"]) length]>0 || [JSON(senderInfo[@"photo"]) length]>0) {
                    EMMessage *mes=[[EMMessage alloc] initWithConversationID:nil from:ext[@"fromType"] to:ext[@"fromType"] body:nil ext:@{@"name":JSON(senderInfo[@"nickName"]),@"image":JSON(senderInfo[@"photo"])}];
                    [_operation insertUserInfo:mes];
                }
            }
            else
            {
                [cell.avatarView.imageView sd_setImageWithURL:[NSURL URLWithString:JSON(senderInfo[@"photo"])] placeholderImage:[UIImage imageNamed:@"message_moren"]];
                cell.titleLabel.text=JSON(senderInfo[@"nickName"]);
            }
        }
        
    } else if (model.conversation.type == EMConversationTypeGroupChat) {
        //            NSString *imageName = @"groupPublicHeader";
        //            if (![model.conversation.ext objectForKey:@"subject"])
        //            {
        EMGroup *group1;
        NSArray *groupArray = [[EMClient sharedClient].groupManager getJoinedGroups];
        for (EMGroup *group in groupArray) {
            if ([group.groupId isEqualToString:model.conversation.conversationId]) {
                group1=group;
                
                NSMutableDictionary *ext = [NSMutableDictionary dictionaryWithDictionary:model.conversation.ext];
                [ext setObject:group.subject forKey:@"subject"];
                [ext setObject:[NSNumber numberWithBool:group.isPublic] forKey:@"isPublic"];
                model.conversation.ext = ext;
                
                break;
                
                //                        break;
            }
            //                }
        }
        //            cell.titleLabel.text=[model.conversation.ext objectForKey:@"subject"];
        //            model.title = [model.conversation.ext objectForKey:@"subject"];
        //            imageName = [[model.conversation.ext objectForKey:@"isPublic"] boolValue] ? @"groupPublicHeader" : @"groupPrivateHeader";
        cell.titleLabel.text=group1.subject;
        cell.avatarView.imageView.image=[UIImage imageNamed:@"qunliao_morenquntouxiang"];
        //            model.avatarImage = [UIImage imageNamed:@""];
    }
    
    if (_dataSource && [_dataSource respondsToSelector:@selector(conversationListViewController:latestMessageTitleForConversationModel:)]) {
        cell.detailLabel.attributedText =  [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:[_dataSource conversationListViewController:_contactListVC latestMessageTitleForConversationModel:model] textFont:cell.detailLabel.font];
    } else {
        cell.detailLabel.attributedText =  [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:[self _latestMessageTitleForConversationModel:model]textFont:cell.detailLabel.font];
    }
    
    cell.timeLabel.text = [self conversationListViewController:_contactListVC latestMessageTimeForConversationModel:model];
    cell.titleLabelFont=[UIFont fontWithName:@"PingFangSC-Regular" size:14];
    cell.detailLabelFont=[UIFont fontWithName:@"PingFangSC-Regular" size:12];
    cell.timeLabelFont=[UIFont fontWithName:@"PingFangSC-Regular" size:12];
    cell.titleLabelColor=DGHColor(50, 50, 50);
    cell.detailLabelColor=DGHColor(168, 168, 168);

    UIView *line=[[UIView alloc] initWithFrame:CGRectMake(10, 69.5, SCREENWIDTH-10, 0.5)];
    line.backgroundColor=RGBACOLOR(221, 221, 221, 1);
    [cell.contentView addSubview:line];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [EaseConversationCell cellHeightWithModel:nil];
//    return 80;
}

- (CGFloat)cellContentViewWith
{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    
    // 适配ios7
    if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait && [[UIDevice currentDevice].systemVersion floatValue] < 8) {
        width = [UIScreen mainScreen].bounds.size.height;
    }
    return width;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    id<IConversationModel> model = [self.dataArr objectAtIndex:indexPath.row];
    if ([_delegate0 respondsToSelector:@selector(didSelectSectionTwoOfModel:)]) {
        [_delegate0 didSelectSectionTwoOfModel:model];
    }
}

#pragma mark 设置可以进行编辑

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

{
    return YES;
}

/**
 
 *  tableView:editActionsForRowAtIndexPath:     // 设置滑动删除时显示多个按钮
 
 *  UITableViewRowAction                        // 通过此类创建按钮
 
 *  1. 我们在使用一些应用的时候，在滑动一些联系人的某一行的时候，会出现删除、置顶、更多等等的按钮，在iOS8之前，我们都需要自己去实现。But，到了iOS8，系统已经写好了，只需要一个代理方法和一个类就搞定了
 
 *  2. iOS8的<UITableViewDelegate>协议多了一个方法，返回值是数组的tableView:editActionsForRowAtIndexPath:方法，我们可以在方法内部写好几个按钮，然后放到数组中返回，那些按钮的类就是UITableViewRowAction
 
 *  3. 在UITableViewRowAction类，我们可以设置按钮的样式、显示的文字、背景色、和按钮的事件（事件在Block中实现）
 
 *  4. 在代理方法中，我们可以创建多个按钮放到数组中返回，最先放入数组的按钮显示在最右侧，最后放入的显示在最左侧
 
 *  5. 注意：如果我们自己设定了一个或多个按钮，系统自带的删除按钮就消失了...
 
 */

#pragma mark 在滑动手势删除某一行的时候，显示出更多的按钮

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        //    // 删除按钮
        id<IConversationModel> model = [self.dataArr objectAtIndex:indexPath.row];
        
        UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
            
//            [model.conversation deleteAllMessages:nil];
//            [[EMClient sharedClient].chatManager deleteConversation:model.conversation.conversationId isDeleteMessages:YES completion:nil];
            
            [self.dataArr removeObjectAtIndex:indexPath.row];
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationTop];
            
            
        }];
        deleteRowAction.backgroundColor = RGBACOLOR(244, 52, 75, 1);
        
        NSString *messageId=model.conversation.conversationId;
        NSString *title=nil;
        
        BOOL isUnread;
        if ([_unreadArr containsObject:messageId]) {
            title=@"取消标记";
            isUnread=YES;
        }
        else
        {
            title=@"标记未读";
            isUnread=NO;
        }
        UITableViewRowAction *unreadRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:title handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
            if (isUnread) {
                [_unreadArr removeObject:messageId];
            }
            else
            {
                [_unreadArr addObject:messageId];
            }
            [[NSUserDefaults standardUserDefaults] setObject:_unreadArr forKey:@"UnreadMessage"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
            [_mainTableView reloadData];
        }];
        unreadRowAction.backgroundColor = RGBACOLOR(255, 201, 48, 1);
        
        
        BOOL isTop;
        if ([_topArr containsObject:messageId]) {
            title=@"取消置顶";
            isTop=YES;
        }
        else
        {
            title=@"置顶";
            isTop=NO;
        }
        UITableViewRowAction *topRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:title handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
            if (isTop) {
                [_topArr removeObject:messageId];
            }
            else
            {
                [_topArr insertObject:messageId atIndex:0];
            }
            [[NSUserDefaults standardUserDefaults] setObject:_topArr forKey:@"TOPMessage"];
            [self loadTableView];
            
        }];
        
        topRowAction.backgroundColor = RGBACOLOR(191, 191, 191, 1);
        
        return @[deleteRowAction,topRowAction];
        
        //        if (model.conversation.type == EMConversationTypeChat)
        //        {
        //            return @[deleteRowAction,unreadRowAction,topRowAction];
        //        }
        //        else
        //        {
        //            return @[deleteRowAction,topRowAction];
        //        }
    }
    return nil;
}

#pragma mark - private
- (NSString *)_latestMessageTitleForConversationModel:(id<IConversationModel>)conversationModel
{
    NSString *latestMessageTitle = @"";
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];
    if (lastMessage) {
        EMMessageBody *messageBody = lastMessage.body;
        switch (messageBody.type) {
            case EMMessageBodyTypeImage:{
                latestMessageTitle = NSEaseLocalizedString(@"message.image1", @"[image]");
            } break;
            case EMMessageBodyTypeText:{
                NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                            convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                latestMessageTitle = didReceiveText;
            } break;
            case EMMessageBodyTypeVoice:{
                latestMessageTitle = NSEaseLocalizedString(@"message.voice1", @"[voice]");
            } break;
            case EMMessageBodyTypeLocation: {
                latestMessageTitle = NSEaseLocalizedString(@"message.location1", @"[location]");
            } break;
            case EMMessageBodyTypeVideo: {
                latestMessageTitle = NSEaseLocalizedString(@"message.video1", @"[video]");
            } break;
            case EMMessageBodyTypeFile: {
                latestMessageTitle = NSEaseLocalizedString(@"message.file1", @"[file]");
            } break;
            default: {
            } break;
        }
    }
    return latestMessageTitle;
}

- (NSString *)_latestMessageTimeForConversationModel:(id<IConversationModel>)conversationModel
{
    NSString *latestMessageTime = @"";
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];;
    if (lastMessage) {
        double timeInterval = lastMessage.timestamp ;
        if(timeInterval > 140000000000) {
            timeInterval = timeInterval / 1000;
        }
        NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"YYYY-MM-dd"];
        latestMessageTime = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeInterval]];
    }
    return latestMessageTime;
}

- (NSString *)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
       latestMessageTimeForConversationModel:(id<IConversationModel>)conversationModel
{
    NSString *latestMessageTime = @"";
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];;
    if (lastMessage) {
        NSLog(@"%lld",lastMessage.timestamp);
//        latestMessageTime = [NSDate formattedTimeFromTimeInterval:lastMessage.timestamp];
        latestMessageTime=[SYS_HelpModel timestampTransformedIntoStandardTime1:lastMessage.timestamp/1000];
    }
    
    
    return latestMessageTime;
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
